#!/usr/bin/env python
#
#Copyright 2011 Velin Georgiev
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

''' Main application file: "webapp/main.py"- handles events related to the /index.html. '''

__author__ = 'Velin Georgiev'

import os
import re
from google.appengine.api import memcache, users
from google.appengine.ext import db, webapp
from google.appengine.ext.webapp.template import render
from google.appengine.ext.webapp.util import run_wsgi_app
from django.utils import feedgenerator
from datamodel import tbl_posts, tbl_comments
#from xml.dom.minidom import parse
#from django.contrib.sitemaps import Sitemap
#from google.appengine.ext.db import djangoforms

#TO DO...
#class Sitemap(Sitemap):
#    changefreq = "never"
#    priority = 0.5
		
class HomePageHandler(webapp.RequestHandler):		
    def get(self):
		strTitlesList = ""
		qrySinglePost = ""
		qrySinglePostId = ""
		qryCommentsList = ""
		comment_id = ""
		categories = ""
		user = users.get_current_user()
		posts = memcache.get('posts')
		#Get the titles list
		selected_category = self.request.get('cat')
		if selected_category != "" and selected_category != "All":
			posts = db.Query(tbl_posts).filter('visible =', True).filter('category =', selected_category).order('-date')
		else:
			posts = db.Query(tbl_posts).filter('visible =', True).order('-date')
		memcache.add('posts', posts)
		#Get categories
		if selected_category == "": selected_category = "All"
		for item in posts:
			strTitlesList = strTitlesList + ('&#167; <a href="/?id=%d&amp;cat=%s">%s</a><br/><br/>' % (item.key().id(), selected_category.replace(" ","+"), item.title))
		if not categories:
			categories = tbl_posts().select_distinct_category()
			memcache.add('categories', categories)
		if self.request.get('id'):
			qrySinglePost = tbl_posts().get_by_id(long(self.request.get('id')))
			#Check if the item exist or is it set to visible
			if (not qrySinglePost) or qrySinglePost.visible == False:
				self.response.out.write("<html><head><body>This item no longer exist.<br/><a href=\"/\" >Go to home page</a></body></head></html>")
				return	
			qrySinglePostId = qrySinglePost.key().id()
		if self.request.get('id'):	
			qryCommentsList = db.Query(tbl_comments).filter('post_id =', long(self.request.get('id'))).filter('visible =', True).order('date')	
			comment_id = self.request.get('comment_id')
		context = {
			'user':      user,
			'login':     users.create_login_url(self.request.uri),
			'logout':    users.create_logout_url(self.request.uri),
			'posts': posts,
			'post_id': qrySinglePost,
			'comments_list': qryCommentsList,
			'categories': categories,
			'titles_list': strTitlesList,
			'article_id': qrySinglePostId,
		}
		tmpl = os.path.join(os.path.dirname(__file__), 'templates','index.html')
		self.response.out.write(render(tmpl, context))
		
class AboutPageHandler(webapp.RequestHandler):		
    def get(self):
		tmpl = os.path.join(os.path.dirname(__file__), 'templates','about.html')
		self.response.out.write(render(tmpl, ""))
		
class SubmitComment(webapp.RequestHandler):
    def post(self):
		post_id = self.request.get('post_id')
		comment = self.request.get('comment')
		cat_ = self.request.get('cat_')
		#Simple Validation
		if re.search("\S", comment) is None:
			self.response.out.write("<html><head><body>You have forgotten to fill in a mandatory field.<br/><a href=\"/\" >Go Back</a></body></head></html>")
			return
		tbl_comments().new_item(post_id, comment)
		self.redirect('/?id=' + str(post_id))

class Feeds(webapp.RequestHandler):
	def get(self):
		items = ""
		posts = db.Query(tbl_posts).filter('visible =', True)
		rss_header = '''<?xml version="1.0" encoding="UTF-8" ?>
		<rss xmlns:content='http://purl.org/rss/1.0/modules/content/' xmlns:dc='http://purl.org/dc/elements/1.1/' xmlns:atom='http://www.w3.org/2005/Atom' version='2.0'>
			<channel>
				<title>Velkata blog</title>
				<link>http://velin-georgiev-blog.appspot.com/</link>
				<description>Feed containing the latest Velkata blog posts</description>
				<language>en-us</language>'''
		for item in posts:
			items =  items + '''<item>
									<title><![CDATA['''+unicode(item.title)+''']]></title>
									<link>http://velin-georgiev-blog.appspot.com/?id='''+str(item.key().id())+'''</link>
									<description><![CDATA['''+unicode(item.content)+''']]></description>
									<category><![CDATA['''+unicode(item.category)+''']]></category>
									<guid>http://velin-georgiev-blog.appspot.com/?id='''+str(item.key().id())+'''</guid>	
								</item>'''
		rss_footer = '''</channel>
			</rss>'''
		self.response.out.write(rss_header+items+rss_footer)
		
application = webapp.WSGIApplication([
    ( '/', HomePageHandler),
	( '/about', AboutPageHandler),
	( '/new_comment', SubmitComment),
	( '/feed', Feeds),
	
], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == '__main__':
    main()